#include "../include/MyTcpClient.hpp"

MyTcpClient::MyTcpClient(const char* p_ip,int p_port):TcpClientSock(p_ip,p_port)
{
    m_maxfd = -1;
    FD_ZERO(&m_rset);
    m_stdin = fileno(stdin);
    if(m_sockfd > m_stdin)
    {
        m_maxfd = m_sockfd;
    }else{
        m_maxfd = m_stdin;
    }
}

MyTcpClient::~MyTcpClient()
{

}

void MyTcpClient::Update()
{
    FD_SET(m_stdin,&m_rset);
    FD_SET(m_sockfd,&m_rset);
    int ret = select(m_maxfd+1,&m_rset,NULL,NULL,NULL);
    if(ret < 0)
    {
        perror("select");
        return;
    }else if(ret == 0)
    {
        return;
    }
    if(FD_ISSET(m_sockfd,&m_rset))
    {
        ret = read(m_sockfd,m_readBuf,BUFSIZ);
        if(ret == 0)
        {
            printf("Server close\n");
            m_clientStop = true;
            return;
        }
        printf("read message form server = [%s]\n", m_readBuf);
        memset(m_readBuf,'\0',BUFSIZ);
    }
    if(FD_ISSET(m_stdin,&m_rset))
    {
        if (fgets(m_sendBuf, BUFSIZ, stdin) == NULL)
        {
            return;
        }
        ret = send(m_sockfd, m_sendBuf, strlen(m_sendBuf), 0);
        memset(m_sendBuf, 0, BUFSIZ);
    }
}